<template>
  <div>
    <div class="table-card">
      <el-card style="margin: 10px 15px 0 15px">
        <el-tabs v-model="activeName"
                 @tab-click="handleClick">
          <el-tab-pane :label="`全部`"
                       name="all">
            <el-row :gutter="20"
                    style="margin-right: 15px; margin-left: -5px"
                    type="flex"
                    v-loading="loading">
              <!-- 定义类别 -->
              <template v-for="(category, index) in [{ name: '大包', value: 1 }, { name: '小包', value: 2 }]">
                <el-col :span="24"
                        :key="index"
                        v-if="true">
                  <h3>{{ category.name }}</h3>
                  <el-row :gutter="20">
                    <el-col v-for="(item, idx) in listData.filter(item => item.category === category.value)"
                            :key="idx"
                            :span="6">
                      <el-card class="box-card clickCard"
                               :shadow="getCardShadow(item.state)"
                               :style="getCardStyle(item.state)"
                               @click.native="getCardAction(item)">
                        <div class="clickCard">
                          <span :class="'header-label-' + getHeaderLabelClass(item.state)">{{ item.roomName }}</span>
                          <el-divider v-if="item.state !== 0"></el-divider>
                          <el-divider v-if="item.state == 0"
                                      class="divider"></el-divider>
                          <span v-if="item.state === 0"
                                class="header-label-idle">空闲中</span>
                          <span v-if="item.state === 1"
                                class="header-label-opened"
                                style="font-size: 13px;">
                            计费时长：{{ item.cashierResult.hour }}小时{{ item.cashierResult.minute }}分钟
                          </span>
                          <span v-if="item.state === 2"
                                class="header-label-idle"
                                style="font-size: 13px;">
                            {{ item.cashierResult.hour }}小时{{ item.cashierResult.minute }}分钟
                          </span>
                          <el-divider v-if="item.state === 2"></el-divider>
                          <span v-if="item.state === 2"
                                class="header-label-idle-hearder"
                                style="font-size: 13px; color: red;">
                            暂停计费中!!
                          </span>
                        </div>
                      </el-card>
                    </el-col>
                  </el-row>
                </el-col>
              </template>
            </el-row>
          </el-tab-pane>
          <el-tab-pane :label="`小包`"
                       name="small">
            <el-row :gutter="20"
                    style="margin-right: 15px; margin-left: -5px"
                    type="flex"
                    v-loading="loading">
              <el-col v-for="(item, index) in filteredSmallPackageData"
                      :key="index"
                      :span="6">
                <el-card :class="{
          'box-card clickCard': true,
          'background-grey': item.state === 0,
          'background-green': item.state === 1,
          'background-yellow': item.state === 2
        }"
                         shadow="hover"
                         @click.native="item.state === 0 ? invoicing(item) : details(item)">

                  <div class="clickCard">
                    <span :class="{
              'header-label-idle-hearder': item.state === 0,
              'header-label-opened-hearder': item.state === 1
            }">
                      {{ item.roomName }}
                    </span>
                    <el-divider class="divider"></el-divider>

                    <span v-if="item.state === 0"
                          class="header-label-idle">空闲中</span>
                    <span v-else-if="item.state === 1"
                          class="header-label-opened"
                          style="font-size: 13px;">
                      计费时长：{{ item.cashierResult.hour }}小时{{ item.cashierResult.minute }}分钟
                    </span>
                    <span v-else-if="item.state === 2"
                          style="font-size: 13px;">
                      {{ item.cashierResult.hour }}小时{{ item.cashierResult.minute }}分钟
                      <el-divider></el-divider>
                      <span class="header-label-idle-hearder"
                            style="color: red;">暂停计费中!!</span>
                    </span>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane :label="`中包`"
                       name="third">
            <el-row :gutter="20"
                    style="margin-right: 15px; margin-left: -5px"
                    type="flex"
                    v-loading="loading">
              <el-col v-for="(item, index) in filteredMediumPackageData"
                      :key="index"
                      :span="6">
                <el-card :class="{
          'box-card clickCard': true,
          'background-grey': item.state === 0,
          'background-green': item.state === 1,
          'background-yellow': item.state === 2
        }"
                         shadow="hover"
                         @click.native="item.state === 0 ? invoicing(item) : details(item)">

                  <div class="clickCard">
                    <span :class="{
              'header-label-idle-hearder': item.state === 0,
              'header-label-opened-hearder': item.state === 1
            }">
                      {{ item.roomName }}
                    </span>
                    <el-divider class="divider"></el-divider>

                    <span v-if="item.state === 0"
                          class="header-label-idle">空闲中</span>
                    <span v-else-if="item.state === 1"
                          class="header-label-opened"
                          style="font-size: 13px;">
                      计费时长：{{ item.cashierResult.hour }}小时{{ item.cashierResult.minute }}分钟
                    </span>
                    <span v-else-if="item.state === 2"
                          style="font-size: 13px;">
                      {{ item.cashierResult.hour }}小时{{ item.cashierResult.minute }}分钟
                      <el-divider></el-divider>
                      <span class="header-label-idle-hearder"
                            style="color: red;">暂停计费中!!</span>
                    </span>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane :label="`大包`"
                       name="second">
            <el-row :gutter="20"
                    style="margin-right: 15px; margin-left: -5px"
                    type="flex"
                    v-loading="loading">
              <el-col v-for="(item, index) in filteredBigPackageData"
                      :key="index"
                      :span="6">
                <el-card :class="{
          'box-card clickCard': true,
          'background-grey': item.state === 0,
          'background-green': item.state === 1,
          'background-yellow': item.state === 2
        }"
                         shadow="hover"
                         @click.native="item.state === 0 ? invoicing(item) : details(item)">

                  <div class="clickCard">
                    <span :class="{
              'header-label-idle-hearder': item.state === 0,
              'header-label-opened-hearder': item.state === 1
            }">
                      {{ item.roomName }}
                    </span>
                    <el-divider class="divider"></el-divider>

                    <span v-if="item.state === 0"
                          class="header-label-idle">空闲中</span>
                    <span v-else-if="item.state === 1"
                          class="header-label-opened"
                          style="font-size: 13px;">
                      计费时长：{{ item.cashierResult.hour }}小时{{ item.cashierResult.minute }}分钟
                    </span>
                    <span v-else-if="item.state === 2"
                          style="font-size: 13px;">
                      {{ item.cashierResult.hour }}小时{{ item.cashierResult.minute }}分钟
                      <el-divider></el-divider>
                      <span class="header-label-idle-hearder"
                            style="color: red;">暂停计费中!!</span>
                    </span>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane :label="`豪包`"
                       name="first">
            <el-row :gutter="20"
                    style="margin-right: 15px; margin-left: -5px"
                    type="flex"
                    v-loading="loading">
              <el-col v-for="(item, index) in filteredLuxuryData"
                      :key="index"
                      :span="6">
                <el-card :class="{
          'box-card clickCard': true,
          'background-grey': item.state === 0,
          'background-green': item.state === 1,
          'background-yellow': item.state === 2
        }"
                         shadow="hover"
                         @click.native="item.state === 0 ? invoicing(item) : details(item)">

                  <div class="clickCard">
                    <span :class="{
              'header-label-idle-hearder': item.state === 0,
              'header-label-opened-hearder': item.state === 1
            }">
                      {{ item.roomName }}
                    </span>
                    <el-divider class="divider"></el-divider>

                    <span v-if="item.state === 0"
                          class="header-label-idle">空闲中</span>
                    <span v-else-if="item.state === 1"
                          class="header-label-opened"
                          style="font-size: 13px;">
                      计费时长：{{ item.cashierResult.hour }}小时{{ item.cashierResult.minute }}分钟
                    </span>
                    <span v-else-if="item.state === 2"
                          style="font-size: 13px;">
                      {{ item.cashierResult.hour }}小时{{ item.cashierResult.minute }}分钟
                      <el-divider></el-divider>
                      <span class="header-label-idle-hearder"
                            style="color: red;">暂停计费中!!</span>
                    </span>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane :label="`卡座`"
                       name="cassette">
            <el-row :gutter="20"
                    style="margin-right: 15px; margin-left: -5px"
                    type="flex"
                    v-loading="loading">
              <el-col v-for="(item, index) in filteredCassetteData"
                      :key="index"
                      :span="6">
                <el-card :class="{
          'box-card clickCard': true,
          'background-grey': item.state === 0,
          'background-green': item.state === 1,
          'background-yellow': item.state === 2
        }"
                         shadow="hover"
                         @click.native="item.state === 0 ? invoicing(item) : details(item)">

                  <div class="clickCard">
                    <span :class="{
              'header-label-idle-hearder': item.state === 0,
              'header-label-opened-hearder': item.state === 1
            }">
                      {{ item.roomName }}
                    </span>
                    <el-divider class="divider"></el-divider>

                    <span v-if="item.state === 0"
                          class="header-label-idle">空闲中</span>
                    <span v-else-if="item.state === 1"
                          class="header-label-opened"
                          style="font-size: 13px;">
                      计费时长：{{ item.cashierResult.hour }}小时{{ item.cashierResult.minute }}分钟
                    </span>
                    <span v-else-if="item.state === 2"
                          style="font-size: 13px;">
                      {{ item.cashierResult.hour }}小时{{ item.cashierResult.minute }}分钟
                      <el-divider></el-divider>
                      <span class="header-label-idle-hearder"
                            style="color: red;">暂停计费中!!</span>
                    </span>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane :label="`大厅`"
                       name="hall">
            <el-row :gutter="20"
                    style="margin-right: 15px; margin-left: -5px"
                    type="flex"
                    v-loading="loading">
              <el-col v-for="(item, index) in filteredListData"
                      :key="index"
                      :span="6">
                <el-card :class="{
          'box-card clickCard': true,
          'background-grey': item.state === 0,
          'background-green': item.state === 1,
          'background-yellow': item.state === 2
        }"
                         shadow="hover"
                         @click.native="item.state === 0 ? invoicing(item) : details(item)">

                  <div class="clickCard">
                    <span :class="{'header-label-idle-hearder': item.state === 0, 'header-label-opened-hearder': item.state === 1}">
                      {{ item.roomName }}
                    </span>
                    <el-divider class="divider"></el-divider>

                    <span v-if="item.state === 0"
                          class="header-label-idle">空闲中</span>
                    <span v-else-if="item.state === 1"
                          class="header-label-opened"
                          style="font-size: 13px;">
                      计费时长：{{ item.cashierResult.hour }}小时{{ item.cashierResult.minute }}分钟
                    </span>
                    <span v-else-if="item.state === 2"
                          style="font-size: 13px;">
                      {{ item.cashierResult.hour }}小时{{ item.cashierResult.minute }}分钟
                      <el-divider></el-divider>
                      <span class="header-label-idle-hearder"
                            style="color: red;">暂停计费中!!</span>
                    </span>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-tab-pane>

        </el-tabs>
      </el-card>
    </div>

    <div class="table-drawer">
      <el-drawer :title="dialogTitle"
                 :visible.sync="openInvoicing"
                 label="rtl"
                 custom-class="invoicing-drawer"
                 ref="invoicingDrawer"
                 size="40%"
                 :show-close="false"
                 @close="resetForm">
        <div class="demo-drawer__content">
          <el-form ref="invoicingData"
                   :model="invoicingData"
                   :rules="rules"
                   size="medium"
                   label-width="100px"
                   class="form-content">
            <el-form-item label="包间类型："
                          prop="categoryChar">
              <span>{{ showData.categoryChar }}</span>
            </el-form-item>
            <el-form-item label="包间号："
                          prop="roomNumber">
              <span>{{ showData.roomName }}</span>
            </el-form-item>
            <el-form-item label="计费规则："
                          prop="tollRules">
              <el-select v-model="invoicingData.tollRules"
                         placeholder="请选择计费规则："
                         :style="{ width: '80%' }">
                <el-option v-for="(item, index) in tollTypeOptions"
                           :key="index"
                           :label="item.label"
                           :value="item.value"
                           :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="顾客人数："
                          prop="customerCount">
              <el-input-number v-model="invoicingData.customerCount"
                               placeholder="顾客人数："
                               :step="1"
                               controls-position="right"
                               :style="{ width: '80%' }"></el-input-number>
            </el-form-item>
            <el-form-item label="开单时间："
                          prop="startTime">
              <el-date-picker type="datetime"
                              v-model="invoicingData.startTime"
                              format="yyyy-MM-dd HH:mm:ss"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              :style="{ width: '80%' }"
                              placeholder="请选择开单时间"
                              clearable>
              </el-date-picker>
            </el-form-item>
          </el-form>
        </div>
        <div class="drawer-button-container">
          <el-button type="primary"
                     @click="confirmInvoicing">确认开单</el-button>
        </div>
      </el-drawer>
    </div>

    <div class="details-drawer">
      <el-drawer :visible.sync="openDetails"
                 label="rtl"
                 custom-class="invoicing-drawer"
                 ref="invoicingDrawer"
                 size="60%"
                 :show-close="false"
                 @close="resetDetailsData">
        <template v-slot:title>
          <div class="drawer-title">
            <span>{{ dialogTitle }}</span>
            <div class="drawer-buttons">
              <el-button type="primary"
                         icon="el-icon-video-pause"
                         size="small"
                         v-if="detailsData.state == 1"
                         @click="pauseBilling(detailsData)"
                         plain>暂停计费</el-button>
              <el-button type="primary"
                         icon="el-icon-video-pause"
                         size="small"
                         v-if="detailsData.state == 2"
                         @click="recoveryBilling(detailsData)"
                         plain>恢复计费</el-button>
              <!-- <el-button type="warning"
                         icon="el-icon-edit-outline"
                         size="small"
                         @click="invoicing"
                         plain>修改订单</el-button> -->
              <el-button type="danger"
                         icon="el-icon-delete"
                         size="small"
                         @click="closeOrder(detailsData)"
                         plain>取消订单</el-button>
              <el-button type="danger"
                         icon="el-icon-close"
                         size="small"
                         @click="closeDetails"></el-button>
            </div>
          </div>
        </template>
        <div class="details-drawer__content">
          <div class="details-drawer__form">
            <el-form ref="detailsData"
                     :model="detailsData"
                     size="medium"
                     label-width="100px"
                     style="width: 90%;">
              <el-col :span="12">
                <el-form-item label="开单时间：">
                  <spn>{{
                    detailsData.cashierResult
                      ? detailsData.cashierResult.startTime
                      : ''
                    }}</spn>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="消费时长：">
                  <span>{{
                    detailsData.cashierResult
                      ? detailsData.cashierResult.hour
                      : ''
                    }}小时{{
                      detailsData.cashierResult
                        ? detailsData.cashierResult.minute
                        : ''
                    }}分钟</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="计费规则：">
                  <span>{{ tollRulesName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="顾客人数：">
                  <span>{{
                    detailsData.cashierResult
                      ? detailsData.cashierResult.customerCount
                      : ''
                    }}</span>
                </el-form-item>
              </el-col>
            </el-form>
          </div>
          <el-divider class="details-divider"></el-divider>

          <div class="details-drawer_table"
               style="height: 100%;">
            <!-- 添加分割线 -->
            <el-tabs v-model="detailsName"
                     @tab-click="handleClick">
              <!-- 包间费用 -->
              <el-tab-pane :label="computedTabLabel"
                           name="tableCost">
                <div class="custom-table-computed">
                  <el-table border
                            style="width: 100%"
                            :data="tableFee"
                            height="100%"
                            class="custom-table">
                    <el-table-column type="index"
                                     label="序号"
                                     align="center"
                                     width="50"></el-table-column>
                    <el-table-column label="包间名"
                                     prop="dialogTitle"
                                     min-width="100"
                                     align="center"></el-table-column>
                    <el-table-column label="开台时间"
                                     prop="startTime"
                                     min-width="180"
                                     align="center"></el-table-column>
                    <el-table-column label="消费时长"
                                     min-width="120"
                                     align="center">
                      <template slot-scope="scope">
                        {{ scope.row.hour }}小时{{ scope.row.minute }}分钟
                      </template>
                    </el-table-column>
                    <el-table-column label="计费规则"
                                     prop="tollRulesName"
                                     min-width="150"
                                     align="center"></el-table-column>
                    <el-table-column label="包间费"
                                     prop="tableFee"
                                     min-width="80"
                                     align="center"></el-table-column>
                    <el-table-column label="超时费"
                                     prop="overtimeFee"
                                     min-width="80"
                                     align="center"></el-table-column>
                    <el-table-column label="服务费"
                                     prop="nightFee"
                                     min-width="80"
                                     align="center"></el-table-column>
                  </el-table>
                </div>

                <span class="table-total">小计金额：<span class="table-total-number">{{ totalCost }}</span> 元</span>
              </el-tab-pane>
              <!-- 商品清单 -->
              <el-tab-pane :label="consumptionTable"
                           name="consumptionCost">
                <div class="custom-table-computed">
                  <el-table border
                            style="width: 100%"
                            :data="consumptionData"
                            class="custom-table">
                    <el-table-column type="index"
                                     label="序号"
                                     align="center"
                                     width="50"></el-table-column>
                    <el-table-column label="商品名"
                                     prop="commodityName"
                                     min-width="100"
                                     align="center"></el-table-column>
                    <el-table-column label="数量"
                                     prop="quantity"
                                     min-width="80"
                                     align="center"></el-table-column>
                    <!-- <el-table-column label="单位"
                                   prop="overtimeFee"
                                   min-width="80"
                                   align="center"></el-table-column> -->
                    <el-table-column label="单价"
                                     prop="unitPrice"
                                     min-width="80"
                                     align="center"></el-table-column>
                    <el-table-column label="合计"
                                     prop="totalAmount"
                                     min-width="80"
                                     align="center"></el-table-column>
                    <el-table-column label="消费时间"
                                     prop="createTime"
                                     min-width="180"
                                     align="center"></el-table-column>
                    <el-table-column label="操作"
                                     min-width="100">
                      <template slot-scope="scope">
                        <el-button type="primary"
                                   icon="el-icon-minus"
                                   circle
                                   class="consumption-button"
                                   size="mini"></el-button>
                        <el-button type="danger"
                                   icon="el-icon-delete"
                                   circle
                                   class="consumption-button"
                                   size="mini"
                                   @click="productDeletion(scope.row.id)"></el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <span class="table-total">小计金额：<span class="table-total-number">{{ consumptionCost }}</span> 元</span>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
        <div class="details-drawer-bottom">
          <div class="details-drawer-bottom-text">
            <span class="details-drawer-bottom-total">应付款：</span>
            <span class="table-total-number">{{ totalAmount }}</span>
            <span>元</span>
          </div>
          <div class="details-drawer-bottom-button">
            <el-button type="success"
                       class="custom-button green-button"
                       icon="el-icon-circle-plus"
                       @click="togDrawer">增加消费</el-button>
            <el-button type="primary"
                       class="custom-button blue-button"
                       icon="el-icon-toilet-paper"
                       @click="showDialog">预计算费用</el-button>
            <el-button type="danger"
                       class="custom-button red-button"
                       icon="el-icon-success"
                       @click="openSettlement">结算订单</el-button>
          </div>
        </div>
      </el-drawer>
    </div>
    <div>
      <consumption :title='consTitle'
                   :tableInfo="tableInfo"
                   :size="'95%'"
                   :direction="'rtl'"
                   ref="drawer"
                   @close="closeDrawer"></consumption>
    </div>

    <div>
      <!-- 引入子组件 -->
      <settlement @confirm="handleConfirm"
                  @refresh="handleRefresh"
                  ref="settlementDialog"
                  :title='settlementTitle'
                  :roomData="tableFee"
                  :productData="consumptionData"
                  :totalMoney="money"
                  :tableInfo="tableInfo" />
    </div>

    <div class="dialogVisible">
      <!-- 弹窗 -->
      <el-dialog title="预计算费用"
                 :visible.sync="dialogVisible"
                 width="30%"
                 @close="handleDialogClose"
                 style="text-align: center;">
        <el-date-picker v-model="stopTime"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择时间">
        </el-date-picker>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <div style="text-align: left;margin-top: 30px;">
            <span style="font-weight: bold;">预计算金额: <span style="color: red;font-weight: bold; font-size: 16px;"> {{
                calculationMoney }}</span></span>
          </div>
          <span slot="footer"
                class="dialog-footer"
                style="text-align: right;margin-top: 30px;">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary"
                       @click="estimateGetMoney">确认</el-button>
          </span>
        </div>
      </el-dialog>
    </div>

  </div>
</template>
<script>
import consumption from './consumption.vue';
import settlement from './settlement.vue';
export default {
  components: {
    consumption,
    settlement,
  },
  name: 'register',
  data() {
    return {
      activeName: 'all',
      detailsName: 'tableCost',
      listData: [],
      dialogTitle: '',
      dialogVisible: false,
      settlementDialog: false,
      calculate: false,
      openDialog: false,
      openInvoicing: false,
      openDetails: false,
      openCons: false,
      tableFee: [], //包间费用信息
      consTitle: '',
      settlementTitle: '',
      tableInfo: {},
      totalAmount: 0,
      money: {}, //包间费用
      consumptionData: [], //商品清单信息
      rules: {
        tollRules: [
          {
            required: true,
            message: '请选择计费规则：',
            trigger: 'change',
          },
        ],
        customerCount: [
          {
            required: true,
            message: '顾客人数',
            trigger: 'blur',
          },
        ],
        startTime: [
          {
            required: true,
            message: '请选择开单时间',
            trigger: 'change',
          },
        ],
      },
      tollTypeOptions: [],
      invoicingData: {
        startTime: '',
        operator: '',
        customerCount: 4,
        roomNumber: '',
        tollRules: null,
        tableId: null,
      },
      //详情数据
      detailsData: {},
      tollRulesName: '',
      stopTime: '', //预计算费用使用的时间
      calculationMoney: 0, //预计算费用的结果
      //主界面展示数据
      showData: {},
    };
  },
  mounted: function () {
    var _this = this;
    this.getList();
    window.bus.$on('blogTableReload', function () {
      _this.getList();
    });
  },
  computed: {
    filteredListData() {
      return this.listData.filter((item) => item.category === 1);
    },
    filteredCassetteData() {
      return this.listData.filter((item) => item.category === 0);
    },
    filteredLuxuryData() {
      return this.listData.filter((item) => item.category === 5);
    },
    filteredBigPackageData() {
      return this.listData.filter((item) => item.category === 4);
    },
    filteredMediumPackageData() {
      return this.listData.filter((item) => item.category === 3);
    },
    filteredSmallPackageData() {
      return this.listData.filter((item) => item.category === 2);
    },
    totalCost() {
      return this.tableFee.reduce((acc, item) => {
        return acc + item.tableFee + item.overtimeFee + item.nightFee;
      }, 0);
    },
    consumptionCost() {
      return this.money.consumption;
    },
    computedTabLabel() {
      return `包间费用 (￥${this.totalCost})`;
    },
    consumptionTable() {
      return `商品清单 (￥${this.consumptionCost})`;
    },
  },
  methods: {
    getCardShadow(state) {
      return state === 0 ? 'hover' : 'hover'; // 根据需要调整不同状态的阴影效果
    },
    getCardStyle(state) {
      switch (state) {
        case 0:
          return { backgroundColor: '#b4b4b4' };
        case 1:
          return { backgroundColor: '#5acd00' };
        case 2:
          return { backgroundColor: '#fdff72' };
        default:
          return {};
      }
    },
    getHeaderLabelClass(state) {
      switch (state) {
        case 0:
          return 'idle-hearder';
        case 1:
          return 'opened-hearder';
        case 2:
          return 'idle-hearder';
        default:
          return '';
      }
    },
    getCardAction(item) {
      switch (item.state) {
        case 0:
          return this.invoicing(item);
        case 1:
        case 2:
          return this.details(item);
        default:
          return null;
      }
    },
    /**
     * 结算订单按钮触发
     */
    async openSettlement() {
      this.settlementTitle = this.dialogTitle + '结算单';
      await this.getMoney(this.tableInfo);
      this.$refs.settlementDialog.settlementDialog = true;
    },
    /**
     * 结算订单 关闭弹窗
     */
    handleConfirm() {
      // 处理结账确认事件
      this.$refs.settlementDialog.settlementDialog = false;
      this.openDetails = false; // 关闭对话框
      this.getList();
    },
    /**
     * 结算订单 刷新账单
     */
    async handleRefresh() {
      await this.getList();
      let foundData = this.listData.find(
        (item) => item.uuid === this.tableInfo.uuid
      );
      if (foundData) {
        this.tableInfo = { ...foundData }; // 使用对象的解构赋值确保 tableInfo 是一个新对象，避免引用问题
      } else {
        // 如果找不到对应的数据，可能需要进行错误处理或者其他逻辑
        console.error('未找到符合条件的数据');
      }
      this.getMoney(this.tableInfo);
      // 处理刷新账单事件
    },
    /**
     * 标签点击事件
     * @param tab
     * @param event
     */
    async handleClick(tab, event) {},
    showDialog() {
      this.stopTime = new Date();
      this.calculationMoney = this.totalAmount;
      this.dialogVisible = true;
    },
    /**
     * 获取商品清单信息
     */
    async getConsumptionData() {
      if (this.tableInfo.uuid) {
        let res = await this.$api.commodityApi.byUuid(
          { uuid: this.tableInfo.uuid },
          {
            loadingTime: 100,
            loadingText: '数据加载中...',
          }
        );
        if (res) {
          this.consumptionData = res;
        }
      }
    },
    togDrawer() {
      this.consTitle = '增加消费(' + this.dialogTitle + ')';
      this.$refs.drawer.toggleDrawer();
    },
    closeDrawer() {
      this.$refs.drawer.closeDrawer();
      this.getMoney(this.tableInfo);
    },
    /**
     * 获取列表
     * @param page
     * @param size
     */
    async getList(page, size) {
      var _this = this;
      let res = await this.$api.tabSetApi.get(
        {},
        {
          loadingTime: 100,
          loadingText: '数据加载中...',
        }
      );
      if (res) {
        this.listData = res;
      }
    },
    /**
     * 点击开单按钮事件
     * @param val
     */
    async invoicing(value) {
      this.tableInfo = value;
      this.dialogTitle = value.categoryChar + '-' + value.roomName;
      this.showData = value;
      this.invoicingData.tollRules = value.billingRules;
      this.getCurrentBeijingTime();
      await this.getOption();
      this.openInvoicing = true;
    },
    /**
     * 已开单点击
     * @param value
     */
    async details(value) {
      this.tableInfo = value;
      this.dialogTitle = value.categoryChar + '-' + value.roomName;
      var tollRuleId = value.cashierResult.tollRules;
      this.detailsData = value;
      let res = await this.$api.tollRuleApi.byId(
        { id: tollRuleId },
        {
          loadingTime: 100,
          loadingText: '数据加载中...',
        }
      );
      if (res) {
        this.tollRulesName = res.billingName;
      }
      this.openDetails = true;
      this.getMoney(value);
    },
    /**
     * 预计算费用
     */
    async estimateGetMoney() {
      if (this.tableInfo.cashierResult) {
        const chargingId = this.tableInfo.cashierResult.chargingId;
        try {
          const res = await this.$api.chargingApi.getMoney(
            {
              id: chargingId,
              uuid: this.tableInfo.uuid,
              stopTime: this.stopTime,
            },
            {
              loadingTime: 100,
              loadingText: '数据加载中...',
            }
          );
          if (res) {
            this.calculationMoney = res.totalAmount;
          }
        } catch (error) {
          throw new Error('费用预估失败：' + error.message);
        }
      } else {
        throw new Error('未找到收费结果信息');
      }
    },
    /**
     * 获取包间计费详情
     */
    async getMoney(value) {
      if (value.cashierResult) {
        var chargingId = value.cashierResult.chargingId;
        let res = await this.$api.chargingApi.getMoney(
          { id: chargingId, uuid: value.uuid },
          {
            loadingTime: 100,
            loadingText: '数据加载中...',
          }
        );
        if (res.tableFee) {
          this.money = res;
          console.log(res.tableFee);
          this.tableFee = res.tableFee;
          this.totalAmount = res.totalAmount;
          if (value.cashierResult) {
            this.tableFee = this.tableFee.map((item) => ({
              ...item,
              ...value.cashierResult,
              dialogTitle: this.dialogTitle,
              tollRulesName: this.tollRulesName,
            }));
          }
        }
        this.getConsumptionData();
      }
    },
    /**
     * 暂停计费
     * @param {Object} value - 当前行信息
     * @returns {Promise<void>}
     */
    async pauseBilling(value) {
      // 验证传入的值是否有效
      if (!this.isValidBillingValue(value)) {
        this.handleError('暂停计费');
        return;
      }

      // 确认暂停计费操作
      const confirmMessage =
        '暂停计费后将不再计时，恢复后将扣除暂停分钟数，确认是否暂停！！';
      const res = await this.confirmAction(confirmMessage);
      if (res) {
        // 执行暂停计费操作
        await this.executeBillingAction(
          this.$api.chargingApi.pause,
          value,
          '暂停计费成功!'
        );
      }
    },

    /**
     * 恢复计费
     * @param {Object} value - 当前行信息
     * @returns {Promise<void>}
     */
    async recoveryBilling(value) {
      // 验证传入的值是否有效
      if (!this.isValidBillingValue(value)) {
        this.handleError('恢复计费');
        return;
      }

      // 确认恢复计费操作
      const confirmMessage = '确认恢复计费后将继续计算时间！！';
      const res = await this.confirmAction(confirmMessage);
      if (res) {
        // 执行恢复计费操作
        await this.executeBillingAction(
          this.$api.chargingApi.recovery,
          value,
          '恢复计费成功!'
        );
      }
    },

    /**
     * 验证传入的值是否包含必要的信息
     * @param {Object} value - 当前行信息
     * @returns {boolean} - 返回值是否有效
     */
    isValidBillingValue(value) {
      return value.cashierResult && value.cashierResult.chargingId;
    },

    /**
     * 处理错误信息并显示通知
     * @param {string} context - 上下文信息，用于描述错误类型
     */
    handleError(context) {
      this.$messageIndex.Notice(
        '错误',
        `系统出现异常请联系管理员(${context})`,
        'error',
        '0'
      );
    },

    /**
     * 显示确认对话框并返回用户的确认结果
     * @param {string} message - 显示的确认信息
     * @returns {Promise<boolean>} - 用户是否确认的结果
     */
    async confirmAction(message) {
      try {
        await this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        return true; // 用户确认
      } catch (error) {
        // 用户取消或发生异常
        return false;
      }
    },

    /**
     * 执行计费操作的方法
     * @param {Function} apiMethod - 调用的API方法
     * @param {Object} value - 当前行信息
     * @param {string} successMessage - 成功后显示的消息
     * @returns {Promise<void>}
     */
    async executeBillingAction(apiMethod, value, successMessage) {
      try {
        // 调用API方法并传递参数
        const res = await apiMethod(
          {
            id: value.cashierResult.chargingId,
            tableId: value.id,
          },
          {
            loadingTime: 100,
            loadingText: '数据加载中...',
          }
        );

        if (res) {
          this.openDetails = false;
          this.resetDetailsData();
          this.$message({
            type: 'success',
            message: successMessage,
          });
          this.getList(); // 更新列表
        } else {
          this.handleError('操作请求失败');
        }
      } catch (error) {
        // 处理异常
        this.handleError('操作请求异常');
      }
    },
    /**
     * 取消订单
     * @param value
     */
    async closeOrder(value) {
      this.$confirm('取消订单后无法恢复订单，请确认是否取消！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let res = await this.$api.chargingApi.cancel(
            {
              id: value.cashierResult.chargingId,
              tableId: value.id,
            },
            {
              loadingTime: 100,
              loadingText: '数据加载中...',
            }
          );
          if (res) {
            this.openDetails = false;
            this.resetDetailsData();
            this.$message({
              type: 'success',
              message: '取消订单成功!',
            });
            this.getList();
          }
        })
        .catch(() => {});
    },
    /**
     * 删除商品根据id
     * @param id 商品id
     */
    async productDeletion(id) {
      this.$confirm('确认取消此商品消费，取消后可重新下单！！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let res = await this.$api.commodityApi.delete(
            {
              id: id,
            },
            {
              loadingTime: 100,
              loadingText: '数据加载中...',
            }
          );
          if (res) {
            this.$message({
              type: 'success',
              message: '取消商品消费成功！',
            });
            this.getMoney(this.tableInfo);
          }
        })
        .catch(() => {});
    },
    handleSuccess() {
      this.openDetails = false;
      this.resetDetailsData();
      this.$message({
        type: 'success',
        message: '恢复计费成功!',
      });
    },

    handleError() {
      this.openDetails = false;
      this.resetDetailsData();
      this.$messageIndex.Notice(
        '错误',
        '系统出现异常请联系管理员(恢复计费)',
        'error',
        '0'
      );
    },
    /**
     * 关闭详情抽屉
     */
    closeDetails() {
      this.openDetails = false;
      this.tableInfo = {};
      this.resetDetailsData;
    },
    async getOption() {
      let res = await this.$api.tollRuleApi.getSelect(
        {},
        {
          loadingTime: 100,
          loadingText: '数据加载中...',
        }
      );
      this.tollTypeOptions = res;
      this.$forceUpdate();
    },
    async confirmInvoicing() {
      this.invoicingData.roomNumber = this.showData.roomName;
      this.invoicingData.tableId = this.showData.id;
      let res = await this.$api.chargingApi.invoicing(this.invoicingData, {
        loadingTime: 100,
        loadingText: '数据加载中...',
      });
      if (res) {
        this.openInvoicing = false;
        this.$message({
          type: 'success',
          message: '开单成功!',
        });
        this.getList();
      }
    },
    filteredCardsData(cardValue) {
      if (cardValue === 'all') {
        return this.tabsData; // 返回所有数据
      } else {
        return this.tabsData.filter((item) => item.categoryId === cardValue);
      }
    },
    /**
     * 获取当前北京时间
     */
    getCurrentBeijingTime() {
      // 获取当前时间的格林威治标准时间（GMT）
      const currentTimeGMT = new Date();
      // 获取本地时间与格林威治时间之间的时区偏移量（以分钟为单位）
      const offsetMinutes = currentTimeGMT.getTimezoneOffset();
      // 将时区偏移量加到当前时间上，得到本地时间
      const currentTimeLocal = new Date(
        currentTimeGMT.getTime() - offsetMinutes * 60 * 1000
      );
      // 将本地时间转换为北京时间（加上8小时）
      currentTimeLocal.setHours(currentTimeLocal.getHours());
      // 将北京时间格式化为字符串
      const formattedBeijingTime = currentTimeLocal
        .toISOString()
        .slice(0, 19)
        .replace('T', ' ');
      // 将北京时间赋值给v-model
      this.invoicingData.startTime = formattedBeijingTime;
    },
    resetForm() {
      this.$refs.invoicingData.resetFields();
    },
    resetDetailsData() {
      this.detailsName = 'tableCost';
      this.totalAmount = 0;
      this.consumptionData = [];
      this.$refs.detailsData.resetFields();
    },
  },
};
</script>
<style scoped lang="scss">
@import '../../styles/register.css';
</style>